<template>
  <div class="scanner">
    <van-nav-bar title="整箱上架(B2C)" left-text="返回" @click-left="onClickLeft"></van-nav-bar>
    <van-row style="margin-top: 0.5rem;" type="flex" justify="center">
      <van-col>
        <van-form>
          <van-field label="货主" v-model="storerName" disabled />
          <van-field label="仓库" v-model="wareHouseName" disabled />
          <van-field label="品牌" v-model="brandName" disabled />
          <van-field
            v-model="putawayParams.recCartonNumber"
            ref="recCartonNumber"
            id="recCartonNumber"
            name="箱号"
            label="箱号"
            placeholder="箱号"
            @focus="recCartonNumberFocusClick"
            @click="recCartonNumberFocusClick"
            :readonly="recCartonNumberReadOnly"
            @keyup.enter.native="verifyRecCartonNumber"
          />
          <van-field
            v-model="putawayParams.locationCode"
            ref="locationCode"
            id="locationCode"
            name="库位"
            label="库位"
            placeholder="库位"
            @focus="locationCodeFocusClick"
            @click="locationCodeFocusClick"
            :readonly="locationCodeReadOnly"
            @keyup.enter.native="verifyLocation"
          />
          <van-field
            v-model="putawayParams.putawayQty"
            ref="putawayQty"
            id="putawayQty"
            name="待上架数量"
            label="待上架数量"
            readonly
            error
            size="large"
            style="margin-top:16px;font-weight"
          />
        </van-form>
      </van-col>
    </van-row>
    <!-- 普通消息响应遮罩层 -->
    <van-overlay :show="showMsgOverlay">
      <div class="wrapper">
        <div>
          <van-row>
            <div class="msgTxt">{{ showMsg }}</div>
          </van-row>
          <van-row style="margin-top:64px">
            <van-col span="24" style="text-align:center">
              <van-button type="primary" @click="closeOverlay()">关闭</van-button>
            </van-col>
          </van-row>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import {mapGetters} from "vuex";
import {
  getStorerSelect,
  getWarehouseSelect,
  getBrandSelect,
  verifyRecCartonNumber,
  verifyLocation,
  excuteBoxPutaway
} from "@/api/biz/putaway/boxPutaway.js";
export default {
  name: "boxPutaway",
  computed: {
    ...mapGetters("user", ["userData"]),
    ...mapGetters("scanner", ["pdaScanData"])
  },
  watch: {
    // 扫描枪操作
    pdaScanData: {
      handler(data) {
        this.scanEvent(data.data);
        let input = document.activeElement.id;
        if (input == "recCartonNumber") {
          this.putawayParams.recCartonNumber = data.data;
          this.verifyRecCartonNumber();
        }
        if (input == "locationCode") {
          this.putawayParams.locationCode = data.data;
          this.verifyLocation();
        }
      },
      deep: true
    }
  },
  created() {
    // 默认焦点聚焦到箱号框
    this.recCartonNumberFocus();
    // 获取当前登录用户名
    this.putawayParams.user = this.userData.sysUserLoginName;
    // 获取货主List
    this.getStorerIdList();
  },
  data() {
    return {
      // 只读选项
      recCartonNumberReadOnly: false,
      locationCodeReadOnly: false,
      // 定义扫描数据
      scanData: [],
      // 货主和仓库
      storerName: "",
      wareHouseName: "",
      brandName: "",
      storerIdList: [],
      wareHouseIdList: [],
      brandIdList: [],
      // 表单参数
      putawayParams: {
        businessType: "B2C",
        storerId: "",
        wareHouseId: "",
        putawayQty: 0,
        recCartonNumber: "",
        locationCode: "",
        user: ""
      },
      // 消息遮罩层参数
      showMsgOverlay: false,
      showMsg: "",
      // 当前得失焦点的文本框
      currentBlurName: ""
    };
  },
  methods: {
    // 扫描枪扫描
    clickEvent() {
      this.scanData = [];
      // this.$toast.success("扫描数据被清理了");
    },
    scanEvent(data) {
      this.scanData.push(data);
    },
    scanErrorEvent() {},
    cellClickEvent() {},
    // 货主下拉框数据获取方法
    getStorerIdList() {
      let userId = this.userData.userId;
      this.storerIdList = [];
      this.wareHouseIdList = [];
      this.brandIdList = [];
      getStorerSelect(userId).then(response => {
        if (response.data.status) {
          for (let i = 0; i < response.data.data.length; i++) {
            this.storerIdList.push({
              name: response.data.data[i].grantValue,
              id: response.data.data[i].grantKey
            });
            // 批量获取仓库数据
            this.getWareHouse(response.data.data[i].grantKey);
          }
        } else {
          this.msgShowTime("此用户无货主权限，请联系管理员授权！");
        }
      });
    },
    //仓库下拉框数据获取方法
    getWareHouse(storerId) {
      let userId = this.userData.userId;
      getWarehouseSelect(storerId, userId).then(response => {
        if (response.data.status) {
          for (let i = 0; i < response.data.data.length; i++) {
            this.wareHouseIdList.push({
              name: response.data.data[i].grantValue,
              id: response.data.data[i].grantKey
            });
            // 获取品牌数据
            this.getBrandIdList(storerId, response.data.data[i].grantKey);
          }
        } else {
          this.msgShowTime("此用户无仓库权限，请联系管理员授权！");
        }
      });
    },
    // 品牌数据
    getBrandIdList(storerId, warehouseId) {
      getBrandSelect(storerId, warehouseId, this.userData.userId).then(response => {
        if (response.data.status) {
          for (let i = 0; i < response.data.data.length; i++) {
            this.brandIdList.push({
              name: response.data.data[i].grantValue,
              id: response.data.data[i].grantKey
            });
          }
        } else {
          this.$toast("此用户无品牌权限，请联系管理员授权！");
        }
      });
    },
    // 箱号框点击或失焦
    recCartonNumberFocusClick() {
      this.recCartonNumberReadOnly = true;
      this.currentBlurName = "recCartonNumber";
      setTimeout(() => {
        this.recCartonNumberReadOnly = false;
      }, 200);
    },
    // 库位框点击或失焦
    locationCodeFocusClick() {
      this.locationCodeReadOnly = true;
      this.currentBlurName = "locationCode";
      setTimeout(() => {
        this.locationCodeReadOnly = false;
      }, 200);
    },
    // 焦点聚焦到箱号框
    recCartonNumberFocus() {
      this.$nextTick(() => {
        this.$refs.recCartonNumber.focus();
      });
    },
    // 光标跳转至库位
    locationFocus() {
      this.$nextTick(() => {
        this.$refs.locationCode.focus();
      });
    },
    // 验证箱号是否存在
    verifyRecCartonNumber() {
      if (this.putawayParams.recCartonNumber == "") {
        this.msgShowTime("请输入箱号！");
        // 定位到箱号
        this.recCartonNumberFocus();
        return false;
      }
      verifyRecCartonNumber(this.putawayParams).then(response => {
        if (response.data.status) {
          // 与登陆权限获取的货主仓库品牌进行比较
          let storerVerify = false;
          let wareHouseVerify = false;
          let brandVerify = false;
          let storerId = "";
          let storerName = "";
          let wareHouseId = "";
          let wareHouseName = "";
          let brandId = "";
          let brandName = "";
          for (let i = 0; i < this.storerIdList.length; i++) {
            if ((this.storerIdList[i].id = response.data.data.storerId)) {
              storerVerify = true;
              storerId = this.storerIdList[i].id;
              storerName = this.storerIdList[i].name;
              break;
            }
          }
          if (storerVerify == true) {
            for (let i = 0; i < this.wareHouseIdList.length; i++) {
              if ((this.wareHouseIdList[i].id = response.data.data.wareHouseId)) {
                wareHouseVerify = true;
                wareHouseId = this.wareHouseIdList[i].id;
                wareHouseName = this.wareHouseIdList[i].name;
                break;
              }
            }
          }
          if (wareHouseVerify == true) {
            for (let i = 0; i < this.brandIdList.length; i++) {
              if ((this.brandIdList[i].id = response.data.data.brandId)) {
                brandVerify = true;
                brandId = this.brandIdList[i].id;
                brandName = this.brandIdList[i].name;
                break;
              }
            }
          }
          if (brandVerify == true) {
            this.putawayParams.putawayQty = Number(response.data.data.allowPutawayQty) - Number(response.data.data.oldPutawayQty);
            // 赋值
            this.putawayParams.storerId = storerId;
            this.putawayParams.wareHouseId = wareHouseId;
            this.putawayParams.brandId = brandId;
            this.storerName = storerName;
            this.wareHouseName = wareHouseName;
            this.brandName = brandName;
            // 箱号验证成功后光标跳转至库位
            this.locationFocus();
          } else {
            // 当前登录账号没有该箱的操作权限，清掉箱号/库位
            this.recCartonNumber = "";
            this.locationCode = "";
            this.locationId = "";
            this.recCartonNumberFocus();
            this.msgShowTime("当前登录账号没有该箱的操作权限！");
          }
        } else {
          this.msgShowTime(response.data.message);
          // 赋值
          this.clearBaseInformation();
          this.putawayParams.recCartonNumber = "";
          this.putawayParams.putawayQty = 0;
        }
      });
    },
    // 验证库位是否存在
    verifyLocation() {
      let recCartonNumber = this.putawayParams.recCartonNumber;
      let locationCode = this.putawayParams.locationCode;
      if (recCartonNumber == "") {
        this.msgShowTime("请先填写箱号！");
        this.putawayParams.locationCode = "";
        this.putawayParams.locationId = "";
        // 定位到箱号
        this.recCartonNumberFocus();
        return false;
      }
      if (locationCode == "") {
        this.msgShowTime("请先填写库位！");
        // 定位到库位
        this.locationFocus();
        return false;
      }
      verifyLocation(this.putawayParams).then(response => {
        if (response.data.status) {
          // 验证成功，赋值库位ID
          this.putawayParams.locationId = response.data.data;
          // this.msgShowTime(response.data.message);
          // 直接执行上架操作
          this.excuteBoxPutaway();
        } else {
          this.putawayParams.locationId = "";
          this.putawayParams.locationCode = "";
          this.msgShowTime(response.data.message);
        }
      });
    },
    // 确认上架
    excuteBoxPutaway() {
      let recCartonNumber = this.putawayParams.recCartonNumber;
      let locationCode = this.putawayParams.locationCode;
      if (recCartonNumber == "" || locationCode == "") {
        this.msgShowTime("箱号和货位不能为空！");
        return false;
      }
      if (this.putawayParams.putawayQty <= 0) {
        this.msgShowTime("当前箱无待上架商品！");
        this.putawayParams.recCartonNumber = "";
        this.putawayParams.locationCode = "";
        this.putawayParams.locationId = "";
        this.clearBaseInformation();
        this.recCartonNumberFocus();
        return false;
      }
      excuteBoxPutaway(this.putawayParams).then(response => {
        if (response.data.status) {
          this.$notify({type: "success", message: response.data.message});
          this.putawayParams.recCartonNumber = "";
          this.putawayParams.locationCode = "";
          this.putawayParams.locationId = "";
          this.putawayParams.putawayQty = 0;
        } else {
          this.putawayParams.recCartonNumber = "";
          this.putawayParams.locationCode = "";
          this.putawayParams.locationId = "";
          this.putawayParams.putawayQty = 0;
          this.msgShowTime(response.data.message);
        }
        this.clearBaseInformation();
        this.recCartonNumberFocus();
      });
    },
    // 清除货主仓库品牌数据
    clearBaseInformation() {
      this.putawayParams.storerId = "";
      this.putawayParams.wareHouseId = "";
      this.putawayParams.brandId = "";
      this.storerName = "";
      this.wareHouseName = "";
      this.brandName = "";
    },
    // 返回上一级页面
    onClickLeft() {
      this.$router.push({
        name: "b2cPutaway"
      });
    },
    // 遮罩层消息展示设置
    msgShowTime(msg) {
      this.showMsg = msg;
      this.showMsgOverlay = true;
      // setTimeout(() => {
      //     this.showMsgOverlay = false;
      // }, 3000);
    },
    // 关闭遮罩
    closeOverlay() {
      this.showMsgOverlay = false;
      // 将焦点回到原位置
      if (this.currentBlurName == "recCartonNumber") {
        this.recCartonNumberFocus();
      } else {
        this.locationFocus();
      }
    }
  }
};
</script>

<style lang="less">
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.msgTxt {
  margin: 8px 83px 0;
  font-size: 18px;
  color: white;
}
</style>
